package com.labichaoka.chaoka.net;

import android.content.Context;

import com.labichaoka.chaoka.base.GlobalParams;
import com.labichaoka.chaoka.base.MyApplication;
import com.labichaoka.chaoka.utils.SharedPreferencesManager;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by admin on 2017/11/2.
 */

public class RetrofitHelper {
    private String CACHE_PATH = "super_card_cache";
    private Context context;
    //private String baseUrl="http://39.107.202.87:8101/";
    //private String baseUrl="https://cscard.labifenqi.com/cscapi/";

    private static RetrofitHelper instance = null;
    private Retrofit mRetrofit = null;

    public static RetrofitHelper getInstance(Context context) {
        if (instance == null) {
            instance = new RetrofitHelper(context);
        }
        return instance;
    }

    private RetrofitHelper(Context mContext) {
        context = mContext;
        init();
    }

    private void init() {
//        //初始化OKHttp
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(logInterceptor)//日志拦截器
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                //.addInterceptor(new RequestInterceptor())
                .addInterceptor(headerInterceptor)
                //.addNetworkInterceptor(new CacheInterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .cache(new Cache(new File(MyApplication.getInstance().getCacheDir(), CACHE_PATH), 1024 * 1024 * 10))
                .build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(GlobalParams.baseUrl)
//                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))//官方默认json数据转换
                .addConverterFactory(CustomGsonConverterFactory.create())//json数据转换
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//将Callable接口转换成Observable接口
                .client(okHttpClient)//网络请求客户端为okhttp
                .build();
    }

    //项目中设置头信息
    private Interceptor headerInterceptor = chain -> {
        Request originalRequest = chain.request();
        RequestBody body = originalRequest.body();
        Request.Builder requestBuilder = originalRequest.newBuilder()
                .addHeader("Accept-Encoding", "gzip")
                .addHeader("Accept", "application/json")
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .method(originalRequest.method(), originalRequest.body());
        requestBuilder.addHeader("lb-session", SharedPreferencesManager.getInstance().getString("token", ""));//添加请求头信息，服务器进行token有效性验证
        Request request = requestBuilder.build();
        return chain.proceed(request);
    };

//    class CacheInterceptor implements Interceptor {
//
//        @Override
//        public Response intercept(Interceptor.Chain chain) throws IOException {
//            //可以进行网络重连接等操作
//            //@link 这篇博客写的很详细:http://www.jianshu.com/p/faa46bbe8a2e
//            Request request = chain.request();
//            Response response = chain.proceed(request);
//            if (NetworkUtil.isNetworkAvailable()) {
//                // 有网络时 设置缓存超时时间0个小时
//                response.newBuilder()
//                        .header("Cache-Control", "public, max-age=" + 0)
//                        .build();
//            } else {
//                response.newBuilder()
//                        .header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24)
//                        .build();
//            }
//            return response;
//        }
//    }

    public RetrofitService getServer() {
        //RetrofitService接口类的实例化
        return mRetrofit.create(RetrofitService.class);
    }
}
